package Lee_code;

import java.util.HashMap;
import java.util.HashSet;

/**
 * @author blh
 * @date 2024年08月05日 10:33
 */
public class Lee_395_85 {
    public int longestSubstring(String s, int k) {
        int len = s.length();
        if (len < k) {
            return 0;
        }
        int maxLen = 0;
        HashMap<Character, Integer> seen = new HashMap<>();
        char[] chars = s.toCharArray();
        for (char aChar : chars) {
            seen.put(aChar, seen.getOrDefault(aChar, 0) + 1);
        }
        HashSet<Character> badChar = new HashSet<>();
        for (Character c : seen.keySet()) {
            if (seen.get(c) < k) {
                badChar.add(c);
            }
        }
        seen.clear();
        for (Character c : chars) {
            if (badChar.contains(c)) {
                // 有坏字符直接清理
                seen.clear();
            } else {
                // 如果没有坏字符
                seen.put(c, seen.getOrDefault(c, 0) + 1);

                maxLen = Math.max(maxLen, seen.values()
                        .stream()
                        .filter(num -> num >= k)
                        .mapToInt(Integer::intValue)
                        .sum());

            }
        }
        return maxLen;
    }

    private boolean judge(HashMap<Character, Integer> seen, int k) {
        for (Character c : seen.keySet()) {
            if (seen.get(c) < k) {
                return false;
            }
        }
        return true;
    }
}
